package kr.pe.osdev.common.util;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class CacheUtil<T> implements Serializable {
    
    private static final long serialVersionUID = -6551786637588950768L;
    
    public static final String CACHE = "cache";
    
    @Autowired
    private static CacheManager cm = CacheManager.create();
    
    public static final String KEY_CODE = "code";
    public static final String KEY_CODE_TREE = "codeTree";
    
    @SuppressWarnings("unchecked")
    public static<T> T get(String cacheName, String key) {
        Cache cache = cm.getCache(cacheName);
        Element element = cache.get(key);
        
        if(element == null) {
            return null;
        }
        
        return (T) element.getValue();
    }
    
    public static<T> void put(String cacheName, String key, T obj) {
        Cache cache = cm.getCache(cacheName);
        Element element = new Element(key, obj);
        cache.put(element);
    }
    
    public static void remove(String cacheName, String key) {
        Cache cache = cm.getCache(cacheName);
        cache.remove(key);
    }
}